package wassalt.client;

import static wassalt.Utils.AppConstants.HTTP_STATUS;
import static wassalt.Utils.AppConstants.URL;

import java.net.URLEncoder;

import org.apache.http.HttpStatus;

import wassalt.Services.HTTPService;
import wassalt.Utils.AppConstants;
import wassalt.Utils.Util;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.widget.Button;
import android.widget.MultiAutoCompleteTextView;
import android.widget.TextView;

/**
 * @author Dalia, Emy Class for creating a CreateNotification 1. Adjusts Text
 *         Header to display "Create CreateNotification" 2. Set the text of the
 *         button to "Offer" 3. set a hint text in the textfield to
 *         "who will you notify"
 * 
 *         4. Insert the appropriate data in the database.
 * */

public class CreateOffer extends CreateNotification {

	final String NewOffer_PATH = "/ManageNotifications/NewNotification_Generic";
	ProgressDialog dialog;
	String TAG = "CreateOffer";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		TextView header = (TextView) findViewById(R.id.title);
		header.setText(R.string.offer_title);

		Button request = (Button) findViewById(R.id.done);
		request.setText(R.string.offer_button);

		MultiAutoCompleteTextView contact = (MultiAutoCompleteTextView) findViewById(R.id.AddContact);
		contact.setHint(R.string.offer_contact_hint);

	}

	/**
	 * @author Emy this method overrides the one in CreateNotification. Its main
	 *         goal is to insert the user's data of the offer Notification in
	 *         the database. The function that will be used for insertion is in
	 *         'ManageNotifications' and is called "newNotification". The
	 *         following method inserts an Offer in the database without dates.
	 *         The input is given to the function using ".putExtras"
	 */
	@Override
	protected void insertDB(long userId, String phone, String place,
			boolean type, int when) {

		dialog = ProgressDialog.show(CreateOffer.this, "",
				getString(R.string.offer_load_msg), true, false);

		Util.setConnecting(this, AppConstants.OFFER_CON_KEY);

		Intent offerServiceIntent = new Intent(this, HTTPService.class);
		offerServiceIntent.setAction(AppConstants.HTTP_INSERT_OFFER_FILTER);
		offerServiceIntent.putExtra(URL, getString(R.string.server_url)
				+ NewOffer_PATH);
		// Loai code "to be approved by Aya
		boolean debug = false;
		if (!debug) {
			offerServiceIntent.putExtra("ntype", AppConstants.OFFER);
			offerServiceIntent.putExtra("idOwner", currentUserId);
			offerServiceIntent.putExtra("phoneReceivers",
					URLEncoder.encode(phoneReceiversJson.toString()));
			offerServiceIntent.putExtra("jsonString", getData().toString());
			startService(offerServiceIntent);
		} else {
			offerServiceIntent.putExtra("ntype", AppConstants.OFFER);
			offerServiceIntent.putExtra("idOwner", currentUserId);
			offerServiceIntent.putExtra("phoneSender", user_phone);
			offerServiceIntent.putExtra("place", place);
			offerServiceIntent.putExtra("type", type);
			offerServiceIntent.putExtra("when", when);
			// if statement to contain el start and end date
			offerServiceIntent.putExtra("phoneReceivers", phoneReceivers);
			startService(offerServiceIntent);
		}
	}

	/**
	 * @author Emy a broadcastreceiver that will handle the reply from the
	 *         server
	 */
	private BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context arg0, Intent offerIntent) {
			try {

				Log.d(TAG, "Resposnse from offer service arrived");
				// updating UI according to response
				int http_status = offerIntent.getExtras().getInt(HTTP_STATUS);
				Util.setDisconnecting(CreateOffer.this,
						AppConstants.OFFER_CON_KEY, "" + http_status);
				if (http_status == HttpStatus.SC_OK) {
					// handling connection success
					Util.setDisconnecting(CreateOffer.this,
							AppConstants.OFFER_CON_KEY, ""
									+ AppConstants.SUCCESS);
					handleSuccess();
				} else {
					Log.d(TAG, "Not Created!");
					throw new Exception();
				}

			} catch (Exception e) {

				Util.setDisconnecting(CreateOffer.this,
						AppConstants.OFFER_CON_KEY, "" + AppConstants.FAILURE);
				handleFailure();
				// handling connection failure!
			} finally {

				if (dialog != null)
					dialog.cancel();
			}

		}
	};

	/**
	 * @author Emy Register the broadcast receiver with each onResume, if not
	 *         connecting and handle the extras sent if any
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		IntentFilter filter = new IntentFilter();
		filter.addAction(AppConstants.HTTP_INSERT_OFFER_FILTER);

		if (!Util.isConnecting(this, AppConstants.OFFER_CON_KEY)) {
			registerReceiver(receiver, filter);
			if (dialog != null)
				dialog.dismiss();
			if (Util.getExtra(this, AppConstants.OFFER_CON_KEY) != null) {
				if (Util.getExtra(this, AppConstants.OFFER_CON_KEY).equals(
						"" + AppConstants.SUCCESS))
					handleSuccess();
				else
					handleFailure();
			}
		}
	}

	/**
	 * @author Emy UnRegister the broadcast receiver with each onPause, if not
	 *         connecting
	 */
	@Override
	protected void onPause() {
		super.onPause();
		if (!Util.isConnecting(this, AppConstants.OFFER_CON_KEY)) {
			unregisterReceiver(receiver);
			Util.clearConnection(this, AppConstants.OFFER_CON_KEY);
		}
	}

	/**
	 * @author Emy this method is called when the status of the server returns
	 *         success. Therefore, the user in this case is returned back to the
	 *         NotificationsListActivity
	 */
	private void handleSuccess() {
		Log.d(TAG, "Created");
		Intent returnToActivity = new Intent();
		returnToActivity.setClass(getApplicationContext(),
				NotificationsListActivity.class);
		startActivity(returnToActivity);
		finish();
	}

	/**
	 * @author Emy this method is called when the status from the server is
	 *         failure of an exception occured where an alertwindow is displayed
	 *         to notify the user that an error occured
	 */
	private void handleFailure() {
		Log.d(TAG, "Exception is caught!");
		// display an error message
		AlertDialog window = new AlertDialog.Builder(CreateOffer.this).create();
		window.setMessage(getString(R.string.error_toast));
	}
}
